﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Xml.Serialization;

namespace CommerceOne.Common
{
    public class SerializeService
    {

        /// <summary>
        /// Serializes the object.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="obj">The obj.</param>
        public void SerializeObject<T>(string fileName, T obj)
        {
            var xmlSerializer = new XmlSerializer(obj.GetType());
            using (var streamWriter = new StreamWriter(fileName, true, Encoding.UTF8))
            {
                xmlSerializer.Serialize(streamWriter, obj);
                streamWriter.Close();
            }
        }

        /// <summary>
        /// Deserializes the object.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName">Name of the file.</param>
        /// <returns></returns>
        public T DeserializeObject<T>(string fileName)
        {
            var xmlSerializer = new XmlSerializer(typeof(T));
            object result = null;
            using (var fileStream = new FileStream(fileName, FileMode.Open))
            {
                result = xmlSerializer.Deserialize(fileStream);
            }

            return (T)result;
        }

        #region Singleton Instance
        private static SerializeService _instance;
        public static SerializeService Instance
        {
            get
            {
                if (_instance == null) _instance = new SerializeService();
                return _instance;
            }
        }
        #endregion
    }
}